<template>
	<view class="test-panel">
		<view class="video-controller" v-if="showVideo">
			<view class="video-box">
				<video :src="$cdn+quelist[cur_qs_index].video" style="width: 100%;height: 100%;" :controls="true"
					:autoplay="true">
				</video>
				<uni-icons type="closeempty" color="#ffffff" size="32" class="closeBtn" @click="showVideo=false">
				</uni-icons>
			</view>
		</view>

		<view v-if="showSubmitTips" class="popcontent">
			<view class="popbox">
				<h1 style="text-align: center;color: white;">
					考试确认窗口
				</h1>
				<view class="opeartips">
					<p>操作提示</p>
					<p>你当前答对：{{realRightNum}},答错：{{realErrorNum}},未答：{{quelist.length-realRightNum-realErrorNum }}</p>
					<p>1.点击【确认交卷】，将提交考试成绩，考试结束！</p>
					<p>2.点击【继续考试】，将关闭此窗口，继续考试！</p>
				</view>
				<view style="padding: 24rpx;">
					<button style="margin: 12rpx;padding:6px 12px;color: #000;font-size: 16px;"
						@click="setTestStaticStatus">
						确认交卷
					</button>
					<button style="margin: 12rpx;padding:6px 12px;color: #000;font-size: 16px;"
						@click="showSubmitTips=false">
						继续考试
					</button>
				</view>
			</view>
		</view>
		<view class="test-statistical" v-if="showStatistical">
			<view class="statistical-box">
				<a-row>
				</a-row>
				<a-row>
					<a-typography-text style="color: #2a91fd;">
						试卷提交
					</a-typography-text>
				</a-row>
				<a-divider style="margin:0px;background-color: #2a91fd;"></a-divider>

				<a-row>
					<a-col :span="12">
						<a-row v-for="(item,index) in infolist">
							<a-col :span="24">
								<a-typography-text>
									{{item[0]}}:
								</a-typography-text>

								<a-typography-text style="margin-left: 18rpx">
									{{userinfo[item[1]]}}
								</a-typography-text>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-typography-paragraph>
									总共:<a-typography-text strong style="color:#000000">{{quelist.length}}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
							<a-col :span="24">
								<a-typography-paragraph>
									正确:<a-typography-text type="success" strong style="font-size: 42rpx;color:#3f77fa">
										{{realRightNum}}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
							<a-col :span="24">
								<a-typography-paragraph>
									错误:<a-typography-text type="warning" strong style="font-size: 42rpx;color:#f33333">
										{{realErrorNum }}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
							<a-col :span="24">
								<a-typography-paragraph>
									未答:<a-typography-text type="info" strong style="font-size: 42rpx;color:#555252">
										{{realNotUse}}
									</a-typography-text> 道</a-typography-paragraph>
							</a-col>
						</a-row>
					</a-col>
					<a-col :span="12">
						<a-row type="flex">
							<a-col>
								<a-typography-paragraph>
									<a-typography-title :level="2">
										{{score >=90 ? '恭喜你成绩及格':'很遗憾，成绩不及格！'}}
									</a-typography-title>
									<a-typography-title :level="2">
										本次成绩{{score}}分
									</a-typography-title>
								</a-typography-paragraph>
							</a-col>
						</a-row>
					</a-col>
				</a-row>

				<a-row class="close-panel" :justify="'center'" type="flex" :gutter="[8,4]">
					<a-col :span="7">
						<a-button block @click="removeQs">
							错题练习
						</a-button>
					</a-col>

					<a-col :span="7">
						<a-button type="primary" block
							@click="()=>{$refs.testController.resetAll();showStatistical=false}">重新开始</a-button>
					</a-col>

					<a-col :span="7">
						<a-button block @click="backpage('DEFAULT')">
							退出测试
						</a-button>
					</a-col>
				</a-row>
			</view>
		</view>
		<a-row style="width:100%" type="flex" class="content">
			<a-col class="info" :sm="5" :md="3" :lg="2">
				<a-card bordered class="info-card" :loading="userinfo==null" v-for="(item,index) in infolist">
					<a-row>
						<a-col :span="24" class="infoitem">
							<a-typography-text>
								{{item[0]}}:
							</a-typography-text>

							<a-typography-text style="margin-left: 18rpx">
								{{userinfo[item[1]]}}
							</a-typography-text>
						</a-col>
					</a-row>
				</a-card>
				<a-card bordered class="info-card">
					<view class="flex-col flex-nowrap infoitem">
						<view>
							已用时间:
						</view>
						<cus-countdown :showDay="false" :hour="0" :minute="0" :second="1"></cus-countdown>
					</view>
				</a-card>
				<a-card bordered>
					<h3 style="font-size:14px;font-weight:bold">
						提示选项
					</h3>
					<view v-for="(item,index) in controllerStatus">
						<view class="flex row flex-nowrap" style="margin-top: 12rpx;">
							<a-checkbox v-model:checked="item.status" :value="item.key"
								@change="onControllerStatusChange">
								{{item.title}}
							</a-checkbox>
						</view>
						<a-divider v-if="index%4==2" style="margin: 12px 0;"></a-divider>
					</view>
				</a-card>

				<a-col bordered style="padding: 0;margin: 0;">
					<a-row style="margin: 0;padding: 0;">
						<a-col :span="24">
							<a-typography-title style="font-size:14px">
								文字大小设置
							</a-typography-title>
						</a-col>
					</a-row>

					<!-- 					<view>
						<uni-data-select style="padding: 0;" v-model="fontType" :localdata="fontFamily"
							@change="fontChange">
						</uni-data-select>
					</view> -->
					<view class="flex-col controller-size">
						<a-button @click="()=>fontSize+=1">
							增大
						</a-button>
						<a-button @click="()=>fontSize-=1">
							减小
						</a-button>
						<a-button @click="()=>fontSize=24">
							默认
						</a-button>
					</view>


					<!-- <a-row>
						<a-col :span="8">
							<a-button @click="()=>fontSize+=1">
								增大
							</a-button>
						</a-col>
						<a-col :span="8">
							
							<a-button @click="()=>fontSize-=1">
								减小
							</a-button>
						</a-col>
						<a-col :span="8">
							<a-button @click="()=>fontSize=24">
								默认
							</a-button>
						</a-col>
					</a-row> -->

				</a-col>
			</a-col>
			<a-col class="controller" :sm="19" :md="21" :lg="22">
				<a-row>
					<a-col style="overflow: scroll;" :sm="18" :md="18" :lg="17">
						<a-skeleton active :loading="!quelist.length"></a-skeleton>
						<block v-if="quelist.length>0">
							<testController ref="testController" :fontType="fontType" :fontSize="fontSize"
								@submit="onSubmitTest" :useCacheAns="last" v-model:rightNum="rightNum" :ans="cur_ans"
								v-model:szl="szl" :ansArr="qs_ans_arr" v-model:errorNum="errorNum" :action="action"
								:quesctionlist="quelist" @changeStatus="changeStatus"
								:controllerStatus="controllerStatusMap" v-model:currentIndex="cur_qs_index">
							</testController>
						</block>
					</a-col>
					<a-col :sm="6" :md="6" :lg="7" class="qs-table-box">
						<a-skeleton active :loading="!quelist.length">
						</a-skeleton>

						<a-row style="width: 100%;">
							<a-col style="width: 8.5%;">
								<span class="th-head" style="font-size: 24rpx;">题目</span>
							</a-col>

							<a-col style="width: 91.5%;">
								<a-row style="width: 100%;">
									<a-col style="width: 10%;" class="th-head" v-for="(item) in 10">
										{{item}}列
									</a-col>
								</a-row>
							</a-col>


						</a-row>

						<a-row class="change-box">
							<a-col style="width: 8.5%;">
								<span class="th-head" v-for="(item,index) in getColumn">
									{{item}}行
								</span>
							</a-col>
							<a-col style="width:91.5%">
								<a-row style="width: 100%;" v-if="quelist.length>0">
									<a-col v-for="(i,d) in quelist" class="a-target"
										@click="()=>$refs.testController.skipQs(d)" :class="{
										'haserror':i.hasError===false,
										'color-change':cur_qs_index==d,
										'color-default':cur_qs_index!=d,
										 'color-error': i.isright!=undefined&& i.isright == false && cur_qs_index !=d,
										 'color-right':i.isright!=undefined  && i.isright == true && cur_qs_index !=d
									}">
										{{d+1}}
										<span class="fabinfo" :class="{'mineFont':i.q_type==1,'maxFont':i.q_type==2}">
											{{i.ansLabel}}
										</span>
									</a-col>
								</a-row>
							</a-col>
						</a-row>


						<view class="qs-table-ans-info ant-card-bordered">
							<view>
								<text style="font-size:16px;font-weight: bold;">
									练习结果
								</text>
							</view>
							<view>
								<text class="test-info">
									抽题数量:<text strong class="test-detail">
										{{quelist.length}}
									</text> 道</text>
							</view>
							<view>
								<text class="test-info">
									答对题目:<text class='test-detail' style="color:#3f77fa">
										{{rightNum}}
									</text> 道</text>
							</view>
							<view>
								<text class="test-info">
									答错题目:<text class='test-detail' style="color:#f33333">
										{{errorNum}}
									</text> 道</text>
							</view>
							<view>
								<text style="font-size: 32rpx">
									未答题目:<text class='test-detail' style="color:#a5a1a5">
										{{quelist.length-rightNum-errorNum}}
									</text> 道</text>
							</view>
							<view>
								<text style="font-size: 32rpx">
									首正率:<text class='test-detail' style="color:#a5a1a5">
										{{szl}}%
									</text> </text>
							</view>
							<view class="controller-box ">
								<a-row :gutter="[2,2]" :type="'flex'" justify="center">
									<a-col :span="8">
										<view class="flex flex-wrap row row-center">
											<a-button type="primary" @click="videoPlay">视频讲解</a-button>
										</view>
									</a-col>
									<a-col :span="8">
										<view class="flex flex-wrap row row-center">
											<a-button type="primary" @click="soundPlay">
												语音讲解
											</a-button>
										</view>
									</a-col>
									<a-col :span="8">
										<view class="flex flex-wrap row row-center">
											<a-button type="primary" @click="soundRead">
												语音读题
											</a-button>
										</view>
									</a-col>
								</a-row>
							</view>
						</view>
					</a-col>
				</a-row>

			</a-col>

		</a-row>
	</view>
</template>

<script>
	import testController from '@/components/test-controller/test-controller.vue';
	import {
		Decimal
	} from 'decimal.js';
	import {
		mapGetters
	} from "vuex"
	import config from '@/admin.config.js'


	const db = uniCloud.database()
	const cmd = db.command
	export default {
		components: {
			testController,
		},
		data() {
			return {
				showSubmitTips: false,
				szl: 100,
				fontType: 'SimHei',
				fontSize: 20,
				fontFamily: [{
						text: "黑体",
						value: 'SimHei'
					},
					{
						text: "宋体",
						value: 'SimSun'
					}
				],
				list: [{
					name: '1',
					id: 1
				}, {
					name: '2',
					id: 2
				}],
				showStatistical: false,
				showVideo: false,
				time: 0,
				localTimeStr: '',
				timeTaskId: null,
				cur_ans: [],
				qs_ans_arr: {},
				rightNum: 0,
				errorNum: 0,
				realRightNum: 0,
				realErrorNum: 0,
				realNotUse: 0,
				cur_qs_index: 0,
				userinfo: null,
				infolist: [
					['姓名', 'studentName'],
					['科目', 'subject'],
					['车型', 'drive'],
					['证件类型', 'cert']
				],
				controllerStatusMap: {},

				controllerStatus: [{
						status: true,
						title: "显示答案",
						key: "SHOW_ANS",
					},
					{
						status: true,
						title: "显示对错",
						key: "SHOW_RIGHT_OR_ERR"
					},
					{
						status: false,
						title: "显示讲解",
						key: "SHOW_EXPLAN"
					},
					{
						status: false,
						title: "语音讲解",
						key: "SOUND_EXPLAN"
					},
					{
						status: true,
						title: "语音提示",
						key: "SOUND_RIGHT_OR_ERR"
					},
					{
						status: false,
						title: "自动语音读题",
						key: "SOUND_QS"
					},
					{
						status: true,
						title: "答错自动语音讲解",
						key: "SOUND_ON_ERR"
					},
					{
						status: true,
						title: "手动翻页",
						key: "TURN_PAGE"
					},
					{
						status: false,
						title: "自动翻页",
						key: "AUTO_PAGE"
					},
					{
						status: false,
						title: "答对翻页",
						key: "RIGHT_PAGE"
					}
				],
				quelist: [],
				labelAns: {
					'0': 'A',
					'1': 'B',
					'2': 'C',
					'3': 'D',
					'4': 'E',
					'5': 'F'
				},
				AnsOfLable: {
					'A': '0',
					'B': '1',
					'C': '2',
					'D': '3',
					'E': '4',
					'F': '5',
				},
				last: false,
				action: 'NORMAL',
				message: ['AUTO_PAGE', 'TURN_PAGE', 'RIGHT_PAGE'],
				soundMessage: ['SOUND_QS', 'SOUND_EXPLAN'],
				subject_page_title: '',
				test_page_title_list: [],
				category: false,
				mode: 'CUSTOM',
				cacheType: 'DEFAULT',
				score: 0
			}
		},
		onLoad(options) {

			this.userinfo = uni.getStorageSync('testpage')
			//	console.log(this.userinfo.model)
			//	console.log(this.userinfo)
			if (this.userinfo.last) {
				this.last = true
			}
			if (this.userinfo.action) {
				this.action = this.userinfo.action
			}
			if (this.userinfo.category) {
				//	console.log(JSON.stringify(this.userinfo))
				this.category = new Boolean(this.userinfo.category)
			}
			if (this.userinfo.model) {
				//	console.log(this.userinfo.model)
				this.model = this.userinfo.model
				//	console.log(this.model)
			}
			for (let s of this.controllerStatus) {
				let {
					status,
					key
				} = s

				this.controllerStatusMap[key] = status
			}


		},

		computed: {
			getColumn() {
				//console.log(Math.floor(this.quelist.length / 10))
				let size = this.quelist.length / 10
				if (size % Math.floor(this.quelist.length / 10) == 0) {
					//	console.log(size)
					return size
				} else {
					//console.log(Math.floor(this.quelist.length / 10) + 1)
					return Math.floor(this.quelist.length / 10) + 1
				}
			},
			...mapGetters({
				isLogin: 'user/isTokenValid'
			})

		},
		watch: {
			fontSize(nv) {
				//console.log(nv)
			},
			cur_qs_index(nv, ov) {
				//console.log(nv)

			}
		},
		onUnload() {
			//	console.log('on destory before')
			if (this.timeTaskId) {
				clearInterval(this.timeTaskId)
			}
			this.$refs.testController.saveCache(this.cacheType)
		},
		onReady() {
			this.getQlist()
		},
		onShow() {
			this.checkToken()
			// if (!this.isLogin) {
			// 	uni.showModal({
			// 		content: '登录状态失效，请重新登录',
			// 		showCancel: false,
			// 		success() {
			// 			uni.reLaunch({
			// 				url: config.login.url
			// 			})
			// 		}
			// 	})
			// }
		},
		methods: {
			checkToken() {
				const self = this
				uniCloud.callFunction({
					name: 'uni-id-sign-cf',
					data: {
						action: 'checkToken'
					}
				}).then(res => {
					if (res.result.code === 30202) {
						uni.showModal({
							content: '登录状态失效，请重新登录',
							showCancel: false,
							success() {
								uni.reLaunch({
									url: config.login.url
								})
							}
						})
					} else {
						if (self.isLogin) {
							//	self.getUserInfo()
						} else {
							if (!self.isLogin) {
								uni.showModal({
									content: '登录状态失效，请重新登录',
									showCancel: false,
									success() {
										uni.reLaunch({
											url: config.login.url
										})
									}
								})
							}
						}
					}
					console.log(res)
				})
			},

			videoPlay() {
				this.showVideo = true
				this.$refs.testController.delInner()
			},
			soundRead() {
				this.showVideo = false
				this.$refs.testController.openSoundQs(true)
			},
			soundPlay() {
				this.showVideo = false
				this.$refs.testController.createdAudio(this.quelist[this.cur_qs_index].sound)
			},
			setTestStaticStatus() {
				this.showSubmitTips = false
				this.showStatistical = true
			},
			onSubmitTest() {
				this.showSubmitTips = true
				this.real_submit()
			},
			real_submit() {

				this.score = this.getScore()
				let form = {
					all: this.quelist.length,
					err: this.realErrorNum,
					right: this.realRightNum,
					username: this.userinfo.studentName,
					score: this.score
				}

				uniCloud.callFunction({
					name: 'addlog',
					data: form
				}).then(res => {
				})

				// this.showStatistical = true
			},
			getScore() {


				let real_right_num = 0
				let real_error_num = 0
				let real_notuse_num = 0
				for (let i = 0; i < this.quelist.length; i++) {
					if (this.quelist[i].ukeys === undefined) {
						real_notuse_num++
					}
					if (this.quelist[i].ukeys === false) {
						real_error_num++
					}
					if (this.quelist[i].ukeys === true) {
						real_right_num++
					}
				}

				this.realRightNum = real_right_num
				this.realErrorNum = real_error_num
				this.real_notuse_num = real_notuse_num



				if (real_right_num == this.quelist.length) {
					return 100
				}

				let maxScore = Decimal(100)
				let leng = Decimal(this.quelist.length)
				let sign_score = maxScore.div(leng).toNumber().toFixed(2)
				let score = Decimal(real_right_num).mul(Decimal(sign_score)).toNumber().toFixed(0)
				return score
			},
			getSid(item) {
				if (item.s_id !== undefined) {
					return item.s_id
				} else {
					//	console.log(item)
					return '11'
				}
			},
			backpage(cacheType) {
				this.cacheType = cacheType
				uni.redirectTo({
					url: '/pages/exercise/exercise'
				})

			},
			fontChange() {},
			removeQs() {
				//	console.log(removeList)
				// this.quelist = this.quelist.filter((e) => {
				// 	return removeList.includes(e.s_id) ? false : e
				// })
				try {
					let temp = []
					for (let s of this.quelist) {
						if (s.ukeys === undefined || s.ukeys === false) {
							temp.push(s)
						}
					}
					if (temp.length == 0) {
						uni.showToast({
							title: "当前暂无错题",
							icon: "none"
						})
						uni.setStorageSync('iserror', false)
						this.$nextTick(() => {
							this.showStatistical = true
						})
						return false
					}
					// this.quelist = temp
					this.$set(this, 'quelist', temp)
					uni.setStorageSync('iserror', true)
					this.$refs.testController.resetError(temp[0])
					this.showStatistical = false
					return true
					// this.quelist = []
					// this.$nextTick(()=>{
					// 	this.quelist = temp
					// })
				} catch (e) {
					uni.showToast({
						title: e,
						duration: 2000,
						icon: "error"
					})
					//TODO handle the exception
				}

				// if (this.action == 'ERROR_LIST') {
				// 	const db = uniCloud.database()
				// 	db.collection('error-qlist').where({
				// 		user_id: this.userinfo.uid,
				// 		q_id: db.command.in(removeList)
				// 	}).remove().then(res => {
				// 		console.log('remove qs=>', res)
				// 	})
				// }
				// for (let s of removeIndexList) {
				// 	//	console.log(s)
				// 	this.quelist.splice(s, 1)
				// }
			},
			changeStatus(meesageType, status) {
				for (let s of this.message) {
					if (s === meesageType) {
						this.controllerStatusMap[meesageType] = status
						this.setKeyStatus(s, true)
					} else {
						this.controllerStatusMap[s] = false
						this.setKeyStatus(s, false)
					}
				}

				for (let s of this.soundMessage) {
					if (s === meesageType) {
						this.controllerStatusMap[meesageType] = status
						this.setKeyStatus(s, true)
					} else {
						this.controllerStatusMap[s] = false
						this.setKeyStatus(s, false)
					}
				}

			},
			setKeyStatus(key, status) {
				for (let s of this.controllerStatus) {
					if (s.key === key) {
						s.status = status
						return
					}
				}
			},
			//e.target.checked/
			onControllerStatusChange(e) {
				this.controllerStatusMap[e.target.value] = e.target.checked
			},
			startTimes() {
				// this.time++
				// if(this.time)
			},
			shuffle(arr) {
				var l = arr.length
				var index, temp
				while (l > 0) {
					index = Math.floor(Math.random() * l)
					temp = arr[l - 1]
					arr[l - 1] = arr[index]
					arr[index] = temp
					l--
				}
				return arr
			},
			resort(struct, s_ans) {

				let arr = []
				let n_ans = [] //重置后的答案
				let s_ans_arr = s_ans.split('|') //重置前答案
				let s_ans_index = []


				for (let s of s_ans_arr) {
					s_ans_index.push(parseInt(this.AnsOfLable[s]))
				}

				struct.forEach((e, i) => {
					if (s_ans_index.includes(e.index)) {
						arr.push(i)
						n_ans.push(this.labelAns[`${i}`])
					}
				})
				return {
					realAns: n_ans.join('|'),
					realIndex: arr.join(',')
				}

			},
			async getLastCache() {
				const result = await db.collection('test-history')
					.where({
						user_id: cmd.eq(this.userinfo.uid)
					}).limit(1)
					.get()
				if (result.result.data.length > 0) {
					return result.result.data
				} else {
					uni.showToast({
						title: "缓存失效请重新练习!",
						duration: 2000,
						icon: "error"
					})
					return false
				}
			},
			async getQlist() {
				let qlstore = null;
				let qsAns = []
				let ql;
				//	console.log(this.model)
				if (this.last) {
					// qlstore = uni.getStorageSync('lastcache').qs
					// this.userinfo = uni.getStorageSync('lastInfo')
					//console.log("user last")
					const cacheReuslt = await this.getLastCache()
					cacheReuslt[0].cachedata = JSON.parse(cacheReuslt[0].cachedata)
					if (cacheReuslt) {
						//	console.log(cacheReuslt)
						// cacheReuslt[0].qlist
						this.rightNum = cacheReuslt[0].cachedata.r_num
						this.errorNum = cacheReuslt[0].cachedata.e_num
						this.cur_qs_index = cacheReuslt[0].cachedata.cur_index
						this.qs_ans_arr = cacheReuslt[0].cachedata.ans
						this.cur_ans = cacheReuslt[0].cachedata.cur_ans
						this.quelist = cacheReuslt[0].cachedata.qlist

					}
					return
				}

				if (qlstore) {
					//console.log(qlstore)
					for (let s of qlstore) {
						if (s.q_type != 2) {
							//	s.q_struct = this.shuffle(s.q_struct)
							s.realProps = this.resort(s.q_struct, s.q_ans)
						}
						s.check = [false, false, false, false, false, false]
						s.hasError = true
						s.haschange = false
					}
					this.quelist = qlstore
					return
				}

				let paper = null
				let test = null
				let paperlist = null
				let qMapSort = new Map()

				if (this.action != 'ERROR_LIST' && this.action != 'ERROR_LIST_ON_MOCK') {
					//console.log(typeof this.category)
					if (this.category == false) {
						paper = await db.collection('subject-page').where({
								s_id: cmd.eq(this.userinfo.id)
							})
							.field('_id,s_id,test_paper_ids,name')
							.get()
						paperlist = paper.result.data[0].test_paper_ids
					} else {
						paperlist = this.userinfo.id
					}
					// console.log(paperlist)

					test = await db.collection('test-paper').where({
							s_id: cmd.in(paperlist)
						})
						.field('_id,s_id,quesction_list,name')
						.get()
					// console.log(test)

					for (let s of test.result.data) {
						let tempArr = []

						for (let d of s.quesction_list) {
							tempArr.push(d)
						}
						qMapSort.set(s.s_id, tempArr)
					}

				} else if (this.action == 'ERROR_LIST_ON_MOCK') {
					const cache = uni.getStorageSync('errlist')
					const allErrorSize = cache.length
					if (allErrorSize <= 0) {
						uni.showModal({
							title: '提示',
							content: '暂无错题',
							success() {
								uni.redirectTo({
									url: '/pages/exercise/exercise'
								})
							}
						})
					}

					let init = 0
					// const tempqlist = []
					// while (init <= allErrorSize) {
					// 	let d = await db.collection('error-qlist').where({
					// 		user_id: db.command.eq(this.userinfo.uid),
					// 	q_id:db.command.in(cache)
					// 	}).field('_id,q_id').limit(500).get()
					// 	init += 500
					// 	for (let s of d.result.data) {
					// 		tempqlist.push(s.q_id)
					// 	}
					// }
					// console.log(tempqlist.length)

					ql = await db.collection('quesction')
						.aggregate()
						.match({
							s_id: cmd.in(cache)
						})
						.limit(allErrorSize)
						.sort({
							s_id: 1
						})
						.end()

					const testpage_q_list = new Map()
					let subjectName = '我的错题'
					this.subject_page_title = subjectName
					// ql.result.data.forEach(E => {		
					// 	testpage_q_list.set(E.s_id, subjectName + '--' + E.name)	
					// 	this.test_page_title_list.push(E.name)
					// })
					//console.log(testpage_q_list.values())
					for (let s of ql.result.data) {
						s['infoname'] = '我的错题'
					}
					//测试增加多选题
					// for (let s of ql.result.data) {
					// 	if (s.q_type == '0') {
					// 		s.q_type = 1
					// 		s.q_ans = 'A|B|C'
					// 		break
					// 	}
					// }

					for (let s of ql.result.data) {
						if (s.q_type != 2) {
							// s.q_struct = this.shuffle(s.q_struct)
							s.realProps = this.resort(s.q_struct, s.q_ans)
						}
						s.check = [false, false, false, false, false, false]
						s.hasError = true
						s.haschange = false
					}

					this.quelist = ql.result.data
					//uni.setStorageSync('qlist', this.quelist)

					return
				} else {

					const allErrorSize = await db.collection('error-qlist').where({
							user_id: db.command.eq(this.userinfo.uid)
						})
						.count()
					if (allErrorSize.result.total <= 0) {
						uni.showModal({
							title: '提示',
							content: '暂无错题',
							success() {
								uni.navigateBack({
									delta: 1
								})
							}
						})
						return
					}

					let init = 0
					const tempqlist = []
					const testMap = new Map()
					while (init < allErrorSize.result.total) {
						let d = await db.collection('error-qlist').where({
							user_id: db.command.eq(this.userinfo.uid)
						}).field('_id,q_id,test_name').limit(500).get()
						init += d.result.data.length
						for (let s of d.result.data) {
							tempqlist.push(s.q_id)
							testMap.set(s.q_id, s.test_name)
						}
					}

					init = 0
					let collSize = 500
					let tempAllSize = tempqlist.length
					let balance = tempAllSize % 500
					let timers = Math.floor(tempAllSize / 500)
					ql = {
						result: {
							data: []
						}
					}
					while (init < tempAllSize) {
						for (let j = 0; j < timers; j++) {
							let tResponse = await db.collection('quesction').where({
								s_id: cmd.in(tempqlist.splice(0, collSize))
							}).limit(collSize).get()
							init += collSize
							for (let s of tResponse.result.data) {
								ql.result.data.push(s)
							}
						}

						let tResponse = await db.collection('quesction').where({
							s_id: cmd.in(tempqlist.splice(0, balance))
						}).limit(balance).get()
						for (let s of tResponse.result.data) {
							ql.result.data.push(s)
						}
						init += balance
					}

					const testpage_q_list = new Map()
					let subjectName = '我的错题'
					this.subject_page_title = subjectName
					// ql.result.data.forEach(E => {		
					// 	testpage_q_list.set(E.s_id, subjectName + '--' + E.name)	
					// 	this.test_page_title_list.push(E.name)
					// })
					//console.log(testpage_q_list.values())
					for (let s of ql.result.data) {
						s['infoname'] = '我的错题' + testMap.get(s.s_id)
					}

					//测试增加多选题
					// for (let s of ql.result.data) {
					// 	if (s.q_type == '0') {
					// 		s.q_type = 1
					// 		s.q_ans = 'A|B|C'
					// 		break
					// 	}
					// }

					for (let s of ql.result.data) {
						if (s.q_type != 2) {
							//	s.q_struct = this.shuffle(s.q_struct)
							s.realProps = this.resort(s.q_struct, s.q_ans)
						}
						s.check = [false, false, false, false, false, false]
						s.hasError = true
						s.haschange = false
					}

					this.quelist = ql.result.data
					//console.log(this.quelist)
					//uni.setStorageSync('qlist', this.quelist)

					return
				}


				const testpage_q_list = new Map()
				const qlist = []
				for (let s of test.result.data) {
					s.quesction_list.forEach(e => {
						qlist.push(e)
					})
				}
				let page = 0
				let size = 500
				let index = 0
				if (this.model == 'order') {
					const collection = db.collection('quesction')
					let tempDataList = []
					let total = qlist.length;

					while (index < total) {
						let arr = [];
						if (qlist.length > 500) {
							arr = qlist.splice(0, size);
						} else {
							arr = qlist;
						}
						const d = await collection.where({
								s_id: cmd.in(arr)
							})
							.limit(arr.length)
							.get()
						index += arr.length;
						for (const s of d.result.data) {
							tempDataList.push(s);
						}
					}
					ql = {
						result: {
							data: tempDataList
						}
					}
				} else if (this.model == 'rand') {

					let tempDataList = []
					let total = qlist.length;
					while (index < total) {
						let arr = [];
						if (qlist.length > 500) {
							arr = qlist.splice(0, size);
						} else {
							arr = qlist;
						}

						const d = await db.collection('quesction')
							.aggregate()
							.match({
								s_id: cmd.in(arr)
							})
							.limit(arr.length)
							.end()

						index += arr.length;
						for (const s of d.result.data) {
							tempDataList.push(s);
						}
					}
					const  shuff = function (array) {
					    for (let i = array.length - 1; i > 0; i--) {
					        // 生成一个从0到i之间的随机索引
					        const j = Math.floor(Math.random() * (i + 1));
					        
					        // 交换元素array[i]和array[j]
					        [array[i], array[j]] = [array[j], array[i]];
					    }
					    return array;
					}
					 tempDataList= shuff(tempDataList )


					ql = {
						result: {
							data: tempDataList
						}
					}


				} else {
					ql = await db.collection('quesction')
						.aggregate()
						.match({
							s_id: cmd.in(qlist)
						})
						.sample({
							size: 100
						})
						.limit(100)
						.sort('s_id', 'asc')
						.end()
				}

				let subjectName = this.userinfo.subjectName
				this.subject_page_title = subjectName
				test.result.data.forEach(E => {
					E.quesction_list.forEach(qe => {
						testpage_q_list.set(qe, subjectName + '--' + E.name)
					})
					// this.test_page_title_list.push(E.name)
				})
				//console.log(testpage_q_list.values())
				for (let s of ql.result.data) {
					s['infoname'] = testpage_q_list.get(s.s_id)
					s['testpaper_name'] = testpage_q_list.get(s.s_id)
				}

				let indexTemp = 0
				//测试增加多选题
				// for (let s of ql.result.data) {
				// 	if (indexTemp == 0) {
				// 		indexTemp++
				// 		continue
				// 	}
				// 	if (s.q_type == '0'  ) {
				// 		s.q_type = 1
				// 		s.q_ans = 'A|B|C'
				// 		break
				// 	}

				// }


				for (let s of ql.result.data) {
					if (s.q_type != 2) {
						//	s.q_struct = this.shuffle(s.q_struct)
						s.realProps = this.resort(s.q_struct, s.q_ans)
					}
					s.check = [false, false, false, false, false, false]
					s.hasError = true
					s.haschange = false
				}
				if (this.model == 'order') {
					let qOrderList = new Map()
					let qlistBySort = []

					for (let i = 0; i < ql.result.data.length; i++) {
						qOrderList.set(ql.result.data[i].s_id, i)
					}
					for (const chapter of qMapSort.keys()) {
						for (let s of qMapSort.get(chapter)) {
							let temp = ql.result.data[qOrderList.get(s)]
							if (temp) {
								qlistBySort.push(temp)
							}
						}
					}
					this.quelist = qlistBySort
				} else {
					this.quelist = ql.result.data
				}

				// uni.setStorageSync('qlist', this.quelist)
			}
		}
	}
</script>

<style scoped lang="scss">
	@import url('./testpage.css');
</style>
